<?php

namespace backend\modules\rbac\controllers;

use Yii;
use backend\modules\rbac\models\Menu;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use mdm\admin\models\Route;

/**
 * MenuController implements the CRUD actions for Menu model.
 */
class MenuController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex()
    {
        $model = new Menu();
        $attributes = Yii::$app->request->get('Menu',[]);
        $attributes = array_filter($attributes);//空的值去掉
        if(Yii::$app->request->isAjax){
            $query = Menu::find()->where($attributes);
            $countQuery = clone $query;
            $data = $query->offset((Yii::$app->request->get('page') - 1) * Yii::$app->request->get('limit'))
                ->limit(Yii::$app->request->get('limit'))
                ->all();
            $res = [];
            foreach ($data as $value){
                $v = $value;
                $v['parent'] = isset($value->menuParent)?$value->menuParent->name:'';
                $res[] = $v;
            }
            return [
                'code'=>0,
                'msg'=>'',
                'count'=>$countQuery->count(),
                'data'=>$res
            ];
        }
        if($attributes){
            $model->setAttributes($attributes);
        }
        $parents = $this->_getAllMenu();

        return $this->render('index', [
            'model' => $model,
            'parents'=>$parents
        ]);
    }

    /**
     * Displays a single Menu model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $parents = $this->_getAllMenu();
        $routes = $this->_getRoutes();

        return $this->render('view', [
            'model' => $model,
            'routes' => $routes,
            'parents' => $parents,
        ]);
    }

    /**
     * Creates a new Menu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Menu();

        if(Yii::$app->request->isAjax){
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return [
                    'status'=>200,
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>500,
                    'msg'=>'保存失败'
                ];
            }
        }
        $parents = $this->_getAllMenu();
        $routes = $this->_getRoutes();

        return $this->render('create', [
            'model' => $model,
            'routes' => $routes,
            'parents' => $parents,
        ]);
    }

    /**
     * Updates an existing Menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Yii::$app->request->isAjax){
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return [
                    'status'=>200,
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>500,
                    'msg'=>'保存失败'
                ];
            }
        }

        $parents = $this->_getAllMenu($model->id);
        $routes = $this->_getRoutes();

        return $this->render('update', [
            'model' => $model,
            'routes' => $routes,
            'parents' => $parents,
        ]);
    }

    /**
     * Deletes an existing Menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        if(Yii::$app->request->isAjax){
            $model = $this->findModel($id);
            $bool = $model->delete();
            if($bool){
                Menu::deleteAll(['parent'=>$model->id]);
                return [
                    'status'=>'200',
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>'500',
                    'msg'=>$model->getErrors()
                ];
            }
        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    private function _getRoutes()
    {
        $routes = [];
        $permissions = Yii::$app->authManager->getPermissions();
        foreach ($permissions as $value){
            $routes[$value->name] = $value->name;
        }
        return $routes;
    }

    private function _getAllMenu($currentId = '')
    {
        $res = [];
        $query = Menu::find();
        if($currentId){
            $query->where(['<>','id', $currentId]);
        }
        $query->orderBy([
            'parent' => SORT_ASC,
            'order'=>SORT_ASC
        ]);
        foreach ($query->all() as $value){
            $res[$value->id] = $value->name;
        }
        return $res;
    }
}
